package com.sms.client.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.MenuBar;
import com.google.gwt.user.client.ui.Tree;
import com.google.gwt.user.client.ui.TreeItem;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.ChartArea;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.LegendPosition;
import com.google.gwt.visualization.client.VisualizationUtils;
import com.google.gwt.visualization.client.visualizations.Gauge;
import com.google.gwt.visualization.client.visualizations.corechart.HorizontalAxisOptions;
import com.google.gwt.visualization.client.visualizations.corechart.LineChart;
import com.google.gwt.visualization.client.visualizations.corechart.Options;
import com.sms.client.ServiceUtil;
import com.sms.client.utils.LoadingBox;
import com.sms.shared.SessionInfo;

public class DashBoardUI extends Composite {

	private String vType;

	private Long siteId;
	
	private String siteName;
	
	private String inverterType;
	
	private String groupNo;

	private String equipmentType;

	private java.util.Date startDate;

	private java.util.Date endDate;

	private ListBox vtypeListBox;

	private DateBox dpFrom;

	private DateBox dpTo;

	private FlexTable appMenuTables;

	private FlexTable chartHeading;

	private FlexTable gaugeHeading;

	private FlexTable chartMainTable;
	
	private HorizontalPanel hpCheckBox;

	private Timer timer;
	
	private String sessionId;
	
	private String partyId;
	
	private String phase;
	public DashBoardUI(Long siteId, String siteName,String groupNo, String vType, String output) {
		this.siteId = siteId;
		this.groupNo = groupNo;
		this.siteName = siteName;
		this.vType = "Hourly";
		this.equipmentType = "Utility";
		VerticalPanel vp = new VerticalPanel();
		initWidget(vp);
		initComponents(vp);
	}

	public void initComponents(VerticalPanel vp) {
		FlexTable flexTable = new FlexTable();
		flexTable.setWidth("100%");
		vp.add(flexTable);
		SessionInfo userSessionInfo = SessionInfo.getSharedInstance();
		String roleName = (String) userSessionInfo.getSessionData(SessionInfo.SESSION_ROLENAME);
		sessionId = (String) userSessionInfo.getSessionData(SessionInfo.JSESSION_ID);
		inverterType = (String)userSessionInfo.getSessionData(SessionInfo.SESSION_INVERTERTYPE);
		partyId = (String)userSessionInfo.getSessionData(SessionInfo.SESSION_PARTYID);
		vtypeListBox = new ListBox();
		vtypeListBox.addItem("Hourly");
		vtypeListBox.addItem("Daily");
		vtypeListBox.addItem("Monthly");
		vtypeListBox.addItem("Yearly");

		vtypeListBox.setItemSelected(0, true);
		vtypeListBox.setWidth("98%");

		appMenuTables = new FlexTable();
		Anchor utilityMenu = new CMenuItem("utility", true, "Utility").getMenuItem();
		FlowPanel fUtility = new FlowPanel();
		fUtility.getElement().setId("utility");
		fUtility.add(utilityMenu);
		appMenuTables.setWidget(0, 0, fUtility);
		addMenuClickHandler(utilityMenu, "Utility");

		Anchor panelMenu = new CMenuItem("panel", false, "Panel").getMenuItem();
		FlowPanel fPanel = new FlowPanel();
		fPanel.getElement().setId("panel");
		fPanel.add(panelMenu);
		appMenuTables.setWidget(1, 0, fPanel);
		addMenuClickHandler(panelMenu, "Panel");

		Anchor inverterMenu = new CMenuItem("inverter", false, "Inverter").getMenuItem();
		FlowPanel fInverter = new FlowPanel();
		fInverter.getElement().setId("inverter");
		fInverter.add(inverterMenu);
		appMenuTables.setWidget(2, 0, fInverter);
		addMenuClickHandler(inverterMenu, "Inverter");

		Anchor batteryMenu = new CMenuItem("battery", false, "Battery").getMenuItem();
		FlowPanel fBattery = new FlowPanel();
		fBattery.getElement().setId("battery");
		fBattery.add(batteryMenu);
		appMenuTables.setWidget(3, 0, fBattery);
		addMenuClickHandler(batteryMenu, "Battery");
		
		if (inverterType.equalsIgnoreCase("Off-Grid With DG")) {
			Anchor generatorMenu = new CMenuItem("generator", false, "D G").getMenuItem();
			FlowPanel fGenerator = new FlowPanel();
			fGenerator.getElement().setId("generator");
			fGenerator.add(generatorMenu);
			appMenuTables.setWidget(4, 0, fGenerator);
			addMenuClickHandler(generatorMenu, "D G");
			
			Anchor allMenu = new CMenuItem("allD", false, "All").getMenuItem();
			FlowPanel fAll = new FlowPanel();
			fAll.getElement().setId("allD");
			fAll.add(allMenu);
			appMenuTables.setWidget(5, 0, fAll);
			addMenuClickHandler(allMenu, "All");
		}else{
			Anchor allMenu = new CMenuItem("allD", false, "All").getMenuItem();
			FlowPanel fAll = new FlowPanel();
			fAll.getElement().setId("allD");
			fAll.add(allMenu);
			appMenuTables.setWidget(4, 0, fAll);
			addMenuClickHandler(allMenu, "All");
		}

		chartHeading = new FlexTable();
		chartHeading.setWidth("100%");

		chartHeading.setWidget(0, 0, new HTML("Chart"));
		chartHeading.getFlexCellFormatter().setWidth(0, 0, "5%");
		chartHeading.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_LEFT);
		chartHeading.getFlexCellFormatter().setStyleName(0, 0, "value_blue_s");
		chartHeading.setStyleName("box_header1");

		chartMainTable = new FlexTable();
//		chartMainTable.setBorderWidth(1);
		chartMainTable.setWidget(0, 0, chartHeading);
		//chartMainTable.getFlexCellFormatter().setWidth(0, 0, "96%");
		chartMainTable.setWidget(0, 1, appMenuTables);
		if (inverterType.equalsIgnoreCase("Off-Grid With DG")) 
			chartMainTable.getFlexCellFormatter().setRowSpan(0, 1, 6);
		else
			chartMainTable.getFlexCellFormatter().setRowSpan(0, 1, 5);
		
		chartMainTable.getFlexCellFormatter().setVerticalAlignment(0, 1, HasVerticalAlignment.ALIGN_TOP);
		chartMainTable.getFlexCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT);
		//chartMainTable.getFlexCellFormatter().setWidth(0, 1, "4%");
		chartMainTable.getFlexCellFormatter().setStyleName(0, 1, "box_bg");
		//chartMainTable.setWidth("100%");

		constructGaugeHeading();
		
		chartMainTable.getFlexCellFormatter().setHeight(0, 0, "5%");
		chartMainTable.getFlexCellFormatter().setHeight(2, 0, "5%");

		final FlexTable filterTable = new FlexTable();
		// filterTable.setWidth("225px");

		filterTable.setWidget(1, 0, new HTML("Type"));
//		filterTable.getFlexCellFormatter().setWidth(1, 0, "44%");
		filterTable.setWidget(2, 0, vtypeListBox);
		final DateTimeFormat format = DateTimeFormat.getFormat("dd/MM/yyyy");

		dpTo = new DateBox();
		dpTo.setWidth("98%");
		dpTo.getDatePicker().setStyleName("myDatePicker");
		dpTo.setFormat(new DateBox.DefaultFormat(format));

		dpFrom = new DateBox();
		dpFrom.setWidth("98%");
		dpFrom.getDatePicker().setStyleName("myDatePicker");
		dpFrom.setValue(new Date());

		dpFrom.setFormat(new DateBox.DefaultFormat(format));

		filterTable.setWidget(3, 0, new HTML("Date"));
		filterTable.setWidget(4, 0, dpFrom);

		vtypeListBox.addChangeHandler(new ChangeHandler() {

			@Override
			public void onChange(ChangeEvent event) {
				int index = vtypeListBox.getSelectedIndex();
				vType = vtypeListBox.getValue(index);
				if (vType.equalsIgnoreCase("Hourly")) {
					dpFrom = new DateBox();
					dpFrom.setWidth("98%");
					dpFrom.getDatePicker().setStyleName("myDatePicker");
					dpFrom.setValue(new Date());

					dpFrom.setFormat(new DateBox.DefaultFormat(format));

					filterTable.setWidget(3, 0, new HTML("Date"));
					filterTable.setWidget(4, 0, dpFrom);
					filterTable.getCellFormatter().setVisible(5, 0, false);
					filterTable.getCellFormatter().setVisible(6, 0, false);
				} else {
					filterTable.setWidget(3, 0, new HTML("From Date"));
					dpFrom = new DateBox();
					dpFrom.setWidth("98%");
					dpFrom.getDatePicker().setStyleName("myDatePicker");
					final DateTimeFormat format = DateTimeFormat.getFormat("dd/MM/yyyy");
					dpFrom.setFormat(new DateBox.DefaultFormat(format));
					filterTable.setWidget(4, 0, dpFrom);
					dpTo.setValue(new Date());
					
					filterTable.getCellFormatter().setVisible(5, 0, true);
					filterTable.getCellFormatter().setVisible(6, 0, true);
				}
			}
		});

		Long mPartyId = Long.valueOf(partyId);
		if (roleName.equalsIgnoreCase("Admin"))
			mPartyId = null;
		ServiceUtil.getMeterServiceAsync().getSites(mPartyId, new AsyncCallback() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onSuccess(Object result) {
				List<ArrayList> dataList = (List) result;
				List<String> locationList = new ArrayList<String>();
				if (dataList.size() > 1) {
					TreeItem rootItem = new TreeItem("Location");
					for (ArrayList list : dataList) {
						if (!locationList.contains((String) list.get(2)))
							locationList.add((String) list.get(2));
					}
					for (String location : locationList) {
						final TreeItem locationItem = new TreeItem(location);
						List<ArrayList> siteDataList = getSiteGroupNo(location, dataList);

						for (ArrayList dataValueList : siteDataList) {
							TreeItem groupNoTree = new TreeItem((String) dataValueList.get(1));
							groupNoTree.setUserObject(dataValueList);
							locationItem.addItem(groupNoTree);
						}
						rootItem.addItem(locationItem);
					}
					Tree tree = new Tree();
					tree.addItem(rootItem);
					filterTable.setWidget(0, 0, tree);
					filterTable.getFlexCellFormatter().setColSpan(0, 0, 2);
					filterTable.getFlexCellFormatter().setWidth(0, 0, "15%");
					tree.addSelectionHandler(new SelectionHandler<TreeItem>() {

						@Override
						public void onSelection(SelectionEvent<TreeItem> event) {
							if (event.getSelectedItem().getUserObject() != null) {
								ArrayList dataValueList = (ArrayList) event.getSelectedItem().getUserObject();
								siteId = (Long) dataValueList.get(0);
								groupNo = (String) dataValueList.get(1);
								siteName = (String) dataValueList.get(3);
								inverterType = (String) dataValueList.get(4);
								setActiveMenu("Utility");
								equipmentType = "Utility";
								
								constructGaugeHeading();
								
								ServiceUtil.getUserLoginServiceAsync().setSessionData(groupNo,inverterType, sessionId, new AsyncCallback() {

									@Override
									public void onFailure(Throwable caught) {
										caught.printStackTrace();
									}

									@Override
									public void onSuccess(Object result) {
										if (result == null)
											return;
										Map resultMap = (Map) result;
										SessionInfo mUserSessionInfo = (SessionInfo) resultMap.get("result");
										SessionInfo.setUserSessionInfo(mUserSessionInfo);
										if (inverterType.equalsIgnoreCase("Off-Grid With DG")) {
											
											if(appMenuTables.getRowCount() >  5)
												appMenuTables.removeRow(5);
											
											Anchor generatorMenu = new CMenuItem("generator", false, "D G").getMenuItem();
											FlowPanel fGenerator = new FlowPanel();
											fGenerator.getElement().setId("generator");
											fGenerator.add(generatorMenu);
											appMenuTables.setWidget(4, 0, fGenerator);
											addMenuClickHandler(generatorMenu, "D G");
											
											Anchor allMenu = new CMenuItem("allD", false, "All").getMenuItem();
											FlowPanel fAll = new FlowPanel();
											fAll.getElement().setId("allD");
											fAll.add(allMenu);
											appMenuTables.setWidget(5, 0, fAll);
											addMenuClickHandler(allMenu, "All");
										}else{
											if(appMenuTables.getRowCount() >  4)
												appMenuTables.removeRow(4);
											Anchor allMenu = new CMenuItem("allD", false, "All").getMenuItem();
											FlowPanel fAll = new FlowPanel();
											fAll.getElement().setId("allD");
											fAll.add(allMenu);
											appMenuTables.setWidget(4, 0, fAll);
											addMenuClickHandler(allMenu, "All");
										}
										
										/*if (inverterType.equalsIgnoreCase("Off-Grid With DG")) {
											Anchor generatorMenu = new CMenuItem("generator", false, "D G").getMenuItem();
											FlowPanel fGenerator = new FlowPanel();
											fGenerator.getElement().setId("generator");
											fGenerator.add(generatorMenu);
											appMenuTables.setWidget(4, 0, fGenerator);
											addMenuClickHandler(generatorMenu, "D G");
											chartMainTable.getFlexCellFormatter().setRowSpan(0, 1, 5);
										}else{
											if(appMenuTables.getRowCount() >  4)
												appMenuTables.removeRow(4);
											chartMainTable.getFlexCellFormatter().setRowSpan(0, 1, 4);
										}*/
										
										if (vType.equalsIgnoreCase("Hourly")) {
											if(dpFrom.getValue() != null){
												populateChartData(equipmentType);
												populateGaugeData();
											}
										}else{
											if(dpFrom.getValue() != null && dpTo.getValue() != null){
												populateChartData(equipmentType);
												populateGaugeData();
											}
										}
										
									}
								});
							}
						}
					});
				}

			}
		});

		filterTable.setWidget(5, 0, new HTML("To Date"));
		filterTable.setWidget(6, 0, dpTo);
		filterTable.getCellFormatter().setVisible(5, 0, false);
		filterTable.getCellFormatter().setVisible(6, 0, false);
		Button goButton = new Button("Go");
		goButton.setStyleName("btn-blue");
		filterTable.setWidget(7, 0, goButton);

		goButton.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				populateChartData(equipmentType);
			}
		});

		filterTable.getFlexCellFormatter().setHorizontalAlignment(7, 0, HasHorizontalAlignment.ALIGN_RIGHT);

		flexTable.setWidget(0, 0, filterTable);
		flexTable.getFlexCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_CENTER);
		populateChartData(equipmentType);
		populateGaugeData();
		refreshPage();
		flexTable.getFlexCellFormatter().setWidth(0, 0, "20%");
		flexTable.getFlexCellFormatter().setVerticalAlignment(0, 0, HasVerticalAlignment.ALIGN_TOP);
		flexTable.setWidget(0, 1, chartMainTable);
		flexTable.getFlexCellFormatter().setWidth(0, 1, "80%");

	}
	
	private void constructGaugeHeading(){
		if (!equipmentType.equalsIgnoreCase("All")) {
			if (gaugeHeading == null) {
				gaugeHeading = new FlexTable();
				gaugeHeading.setWidth("100%");
				gaugeHeading.setWidget(0, 0, new HTML(""));
				if (inverterType.equalsIgnoreCase("Off-Grid With DG"))
					gaugeHeading.setWidget(0, 1, new HTML(equipmentType + " - " + " Phase I"));
				else
					gaugeHeading.setWidget(0, 1, new HTML(equipmentType));
				gaugeHeading.getFlexCellFormatter().setWidth(0, 0, "87%");
				gaugeHeading.getFlexCellFormatter().setWidth(0, 1, "13%");
				gaugeHeading.getFlexCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_RIGHT);
				gaugeHeading.getFlexCellFormatter().setStyleName(0, 1, "value_blue_s");
				gaugeHeading.setStyleName("box_header1");
				chartMainTable.setWidget(2, 0, gaugeHeading);
			}
			showPhaseMenu();
		}else{
			if(hpCheckBox == null)
				hpCheckBox = new HorizontalPanel();
			hpCheckBox.setStyleName("box_bg");
			chartMainTable.setWidget(2, 0, hpCheckBox);
			chartMainTable.getFlexCellFormatter().setWidth(2, 0, "100%");
			chartMainTable.getFlexCellFormatter().setHorizontalAlignment(2, 0, HasHorizontalAlignment.ALIGN_RIGHT);
			chartMainTable.getFlexCellFormatter().setVerticalAlignment(2, 0, HasVerticalAlignment.ALIGN_TOP);
		}
	}

	private void refreshPage() {
		timer = new Timer() {
			public void run() {
				populateGaugeData();
				populateChartData(equipmentType);
				refreshPage();
			}
		};
		// Schedule the timer to run once in 5 minutes.
		timer.schedule(5 * 60 * 1000);
	}

	public void cancelTimer() {
		timer.cancel();
	}

	private List getSiteGroupNo(String location, List<ArrayList> siteList) {
		List dataList = new ArrayList();
		for (ArrayList list : siteList) {
			if (((String) list.get(2)).equalsIgnoreCase(location)) {
				dataList.add(list);
			}

		}
		return dataList;
	}

	private void addMenuClickHandler(final Anchor anchor, final String menuName) {
		anchor.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				setActiveMenu(menuName);
				equipmentType = menuName;
				//System.err.println("inverterType : "+inverterType + " equipmentType "+equipmentType +":" +chartMainTable.getRowCount());
				constructGaugeHeading();
				populateChartData(equipmentType);
				populateGaugeData();

			}
		});
	}
	
	private void setActiveMenu(String menuName){
		int rCount = appMenuTables.getRowCount();
		for (int index = 0; index < rCount; index++) {
			FlowPanel flowPanel = (FlowPanel) appMenuTables.getWidget(index, 0);
			if (((Anchor) flowPanel.getWidget(0)).getText().equalsIgnoreCase(menuName))
				((Anchor) flowPanel.getWidget(0)).setStyleName("active");
			else
				((Anchor) flowPanel.getWidget(0)).removeStyleName("active");
		}
	}

	private void populateChartData(final String equpType) {
		startDate = dpFrom.getValue();
		
		if (vType.equalsIgnoreCase("Hourly")) {
			endDate = null;
			if (startDate == null) {
				Window.alert("Please choose the date");
				return;
			}
		} else {
			endDate = dpTo.getValue();
			if (startDate == null || endDate == null) {
				Window.alert("Please choose the from/to date");
				return;
			}
		}
		LoadingBox.getSharedInstance().show();
		String chartTitle = "";
		if (equipmentType.equalsIgnoreCase("Panel"))
			chartTitle = "Solar Generation";
		else if (equipmentType.equalsIgnoreCase("Utility"))
			chartTitle = "Grid Consumption";
		else if (equipmentType.equalsIgnoreCase("Inverter"))
			chartTitle = "Facility Consumption";
		else if (equipmentType.equalsIgnoreCase("Battery"))
			chartTitle = "Battery Status";
		else if (equipmentType.equalsIgnoreCase("D G"))
			chartTitle = "DG Consumption";

		String dateRange = "";
		if (vType.equalsIgnoreCase("Hourly"))
			dateRange = dateRange + DateTimeFormat.getFormat("dd/MM/yyyy").format(startDate);
		else {
			dateRange = dateRange + DateTimeFormat.getFormat("dd/MM/yyyy").format(startDate);
			dateRange = dateRange + " - ";
			dateRange = dateRange + DateTimeFormat.getFormat("dd/MM/yyyy").format(endDate);
		}

		chartHeading.setWidget(0, 1, new HTML(chartTitle));
		chartHeading.getFlexCellFormatter().setWidth(0, 1, "63%");
		chartHeading.getFlexCellFormatter().setHorizontalAlignment(0, 1, HasHorizontalAlignment.ALIGN_CENTER);
		chartHeading.getFlexCellFormatter().setStyleName(0, 1, "body_txt_black_b");

		HTML dateHtml = new HTML("<span class=\"value_blue_s\">" + vType + "</span><span class=\"body_txt_black_b\"> (" + dateRange + ")</span>");
		chartHeading.setWidget(0, 2, dateHtml);
		chartHeading.getFlexCellFormatter().setWidth(0, 2, "32%");
		chartHeading.getFlexCellFormatter().setHorizontalAlignment(0, 2, HasHorizontalAlignment.ALIGN_RIGHT);
		System.err.println(" siteId:" + siteId + " groupNo: " + groupNo + " equipmentType :" + equipmentType + " startDate:" + startDate + " endDate:" + endDate);
		final boolean isDGConfigured = inverterType.equalsIgnoreCase("Off-Grid With DG") ? true : false;
		ServiceUtil.getMeterServiceAsync().getDashBoardData(siteId, groupNo, equpType, vType, startDate, endDate, isDGConfigured,new AsyncCallback() {

			@Override
			public void onFailure(Throwable caught) {
				LoadingBox.getSharedInstance().hide();

			}

			@Override
			public void onSuccess(Object result) {
				LoadingBox.getSharedInstance().hide();
				Map dataMap = (Map) result;
				loadChart(dataMap,isDGConfigured,equpType);
			}
		});

	}
	
	private void showPhaseMenu(){
		if (inverterType.equalsIgnoreCase("Off-Grid With DG") && (equipmentType.equalsIgnoreCase("Utility") || equipmentType.equalsIgnoreCase("D G"))) {
			phase = "Phase I";
			// gaugeHeading.setWidget(0, 1, new HTML(equipmentType
			// +" - "+" Phase I"));
			MenuBar menuBar = new MenuBar();
			menuBar.addStyleName("remon-MenuBar");
			menuBar.addItem("Phase I", new Command() {

				@Override
				public void execute() {
					phase = "Phase I";
					gaugeHeading.setWidget(0, 1, new HTML(equipmentType + " - " + " Phase I"));
					populateGaugeData();
				}
			});

			menuBar.addItem("Phase II", new Command() {

				@Override
				public void execute() {
					phase = "Phase II";
					gaugeHeading.setWidget(0, 1, new HTML(equipmentType + " - " + " Phase II"));
					populateGaugeData();
				}
			});
			menuBar.addItem("Phase III", new Command() {

				@Override
				public void execute() {
					phase = "Phase III";
					gaugeHeading.setWidget(0, 1, new HTML(equipmentType + " - " + " Phase III"));
					populateGaugeData();
				}
			});

			chartMainTable.setWidget(4, 0, menuBar);
			chartMainTable.getFlexCellFormatter().setHorizontalAlignment(4, 0, HasHorizontalAlignment.ALIGN_RIGHT);
			chartMainTable.getFlexCellFormatter().setVerticalAlignment(4, 0, HasVerticalAlignment.ALIGN_TOP);
		}else{
			phase = null;
			if(chartMainTable.getRowCount() > 4)
				chartMainTable.removeRow(4);
		}
	}

	private void populateGaugeData() {
		//System.err.println("equipmentType : "+equipmentType + " inverterType : "+inverterType);
		LoadingBox.getSharedInstance().show();
		if(!equipmentType.equalsIgnoreCase("All")){
			if(phase != null)
				gaugeHeading.setWidget(0, 1, new HTML(equipmentType+" - "+phase));
			else
				gaugeHeading.setWidget(0, 1, new HTML(equipmentType));
			hpCheckBox = null;
			ServiceUtil.getMeterServiceAsync().getGaugeMap(siteId, groupNo, equipmentType,phase, new AsyncCallback() {

				@Override
				public void onFailure(Throwable caught) {
					LoadingBox.getSharedInstance().hide();

				}

				@Override
				public void onSuccess(Object result) {
					LoadingBox.getSharedInstance().hide();
					Map dataMap = (Map) result;
					Map gaugeConf = (Map) dataMap.get("GaugeConf");
					System.err.println("gaugeConf" + gaugeConf.size());
					List gaugeValueList = (List) dataMap.get("GaugeValue");
					loadGauge(gaugeConf, gaugeValueList);
					String lastUpdatedDate = null;
					if (gaugeValueList != null && gaugeValueList.size() > 0) {
						lastUpdatedDate = (String) gaugeValueList.get(0);
						String[] lastUpdatedArray = lastUpdatedDate.split(";");
						HTML titleHtml = new HTML("<span class=\"value_blue_s\">" + lastUpdatedArray[0] + "</span><span class=\"body_txt_black_b\">" + lastUpdatedArray[1] + "</span>");
						gaugeHeading.setWidget(0, 0, titleHtml);
						
					}

				}
			});
		}else{
			while(chartMainTable.getRowCount() > 3){
				chartMainTable.removeRow(3);
			}
			CheckBox cbPanel = new CheckBox("Panel");
			cbPanel.setValue(true);
			cbPanel.setEnabled(false);
			hpCheckBox.clear();
			hpCheckBox.setHeight("20px");
			hpCheckBox.add(cbPanel);
			hpCheckBox.setCellWidth(cbPanel, "100px");
			hpCheckBox.setCellVerticalAlignment(cbPanel, HasVerticalAlignment.ALIGN_MIDDLE);
//			hpCheckBox.setCellHeight(cbPanel, "20px");
			CheckBox cbInverter = new CheckBox("Inverter");
			hpCheckBox.add(cbInverter);
			cbInverter.setValue(true);
			hpCheckBox.setCellVerticalAlignment(cbInverter, HasVerticalAlignment.ALIGN_MIDDLE);
			hpCheckBox.setCellWidth(cbInverter, "100px");
//			CheckBox cbBattery = new CheckBox("Battery");
//			hpCheckBox.add(cbBattery);
//			cbBattery.setValue(true);
			CheckBox cbUtility = new CheckBox("Utility");
			hpCheckBox.add(cbUtility);
			cbUtility.setValue(true);
			hpCheckBox.setCellVerticalAlignment(cbUtility, HasVerticalAlignment.ALIGN_MIDDLE);
			hpCheckBox.setCellWidth(cbUtility, "100px");
			if (inverterType.equalsIgnoreCase("Off-Grid With DG")) {
				CheckBox cbDG = new CheckBox("Diesel Generator");
				cbDG.setValue(true);
				hpCheckBox.add(cbDG);
				hpCheckBox.setCellVerticalAlignment(cbDG, HasVerticalAlignment.ALIGN_MIDDLE);
				hpCheckBox.setCellWidth(cbDG, "150px");
			}
			Button btnApply = new Button("Apply");
			btnApply.setStyleName("btn-blue");
			hpCheckBox.add(btnApply);
			hpCheckBox.setCellWidth(btnApply,"50px");
			hpCheckBox.setCellHorizontalAlignment(btnApply, HasHorizontalAlignment.ALIGN_RIGHT);
			btnApply.addClickHandler(new ClickHandler() {
				
				@Override
				public void onClick(ClickEvent event) {
					StringBuffer sbEquipmentType = new StringBuffer();
					for(int wIndex = 0; wIndex < hpCheckBox.getWidgetCount(); wIndex++){
						Widget widget = hpCheckBox.getWidget(wIndex);
						if(widget instanceof CheckBox){
							if(((CheckBox)widget).getValue())
								sbEquipmentType.append(((CheckBox)widget).getText()).append(",");
						}
					}
					
					sbEquipmentType = new StringBuffer(sbEquipmentType.substring(0, sbEquipmentType.length()-1));
					//equipmentType = sbEquipmentType.toString();
					populateChartData(sbEquipmentType.toString());
				}
			});
//			hpCheckBox.add(child)
			gaugeHeading = null;
			//chartMainTable.setWidget(3, 0, new HTML());
		}
	}

	private void loadChart(final Map chartMap,final boolean isDGConfigured,final String equpType) {
		Runnable onLoadCallback = new Runnable() {
			public void run() {
				DataTable data = DataTable.create();
				if (vType.equalsIgnoreCase("Hourly"))
					data.addColumn(ColumnType.STRING, "Hour");
				if (vType.equalsIgnoreCase("Daily"))
					data.addColumn(ColumnType.STRING, "Date");
				if (vType.equalsIgnoreCase("Monthly"))
					data.addColumn(ColumnType.STRING, "Month");
				if (vType.equalsIgnoreCase("Yearly"))
					data.addColumn(ColumnType.STRING, "Year");
				
				if(equipmentType.equalsIgnoreCase("All")){
					data.addColumn(ColumnType.NUMBER, "Panel (kWh)");
					data.addColumn(ColumnType.NUMBER, "Inverter (kWh)");
//					data.addColumn(ColumnType.NUMBER, "Battery (V)");
					data.addColumn(ColumnType.NUMBER, "Utility (kWh)");
					if(isDGConfigured)
						data.addColumn(ColumnType.NUMBER, "Diesel Generator (kWh)");
				}else if(equipmentType.equalsIgnoreCase("Battery")){
					data.addColumn(ColumnType.NUMBER, "V");
				}else{
					data.addColumn(ColumnType.NUMBER, "kWh");
				}
				StringBuffer sbColors = new StringBuffer("[");	
				data.addRows(chartMap.size());
				Set set = chartMap.entrySet();
				Iterator i = set.iterator();
				int rowIndex = 0;
				Map panelMap = null;
				Map inverterMap = null;
				Map utilityMap = null;
				Map dgMap = null;
				Map batteryMap = null;
				int rowCount = 0;
				while (i.hasNext()) {
					Map.Entry me = (Map.Entry) i.next();
					if (!equpType.contains(",") && !equpType.equalsIgnoreCase("ALL")) {
						String key = (me.getKey() instanceof String) ? (String) me.getKey() : String.valueOf(me.getKey());
//						System.err.println("rowIndex:" + rowIndex);
						data.setValue(rowIndex, 0, key);
						if (me.getValue() != null) {
							ArrayList dataValueList = (ArrayList) me.getValue();
							if (dataValueList.size() > 0)
								data.setValue(rowIndex, 1, (Double) dataValueList.get(0));
						}
						rowIndex++;
					} else {
						String key = (me.getKey() instanceof String) ? (String) me.getKey() : String.valueOf(me.getKey());
						if (key.equalsIgnoreCase("Panel")) {
							if (me.getValue() != null) {
								panelMap = (LinkedHashMap) me.getValue();
								sbColors.append("Green,");
								rowCount = panelMap.size();
							}
						}

						if (key.equalsIgnoreCase("Inverter")) {
							if (me.getValue() != null) {
								inverterMap = (LinkedHashMap) me.getValue();
								sbColors.append("DarkGray,");
							}
						}

						if (key.equalsIgnoreCase("Utility")) {
							if (me.getValue() != null) {
								utilityMap = (LinkedHashMap) me.getValue();
								sbColors.append("Red,");
							}
						}

						if (key.equalsIgnoreCase("Battery")) {
							if (me.getValue() != null) {
								batteryMap = (LinkedHashMap) me.getValue();
								sbColors.append("Blue,");
							}
						}

						if (key.equalsIgnoreCase("Diesel Generator")) {
							if (me.getValue() != null) {
								dgMap = (LinkedHashMap) me.getValue();
								sbColors.append("IndianRed,");
							}
						}

					}
				}
				
				
				rowIndex = 0;
				if(panelMap != null){
					if(sbColors.length() > 0){
						sbColors=	new StringBuffer(sbColors.substring(0, sbColors.length()-1));
						sbColors.append("]");
					}
					data.addRows(rowCount);
					Set panelSet = panelMap.entrySet();
					Iterator panelIterator = panelSet.iterator();
					
					while(panelIterator.hasNext()){

						Map.Entry me = (Map.Entry) panelIterator.next();
						int columnIndex = 0;	
						Object key = me.getKey();
						String xAxisValue = (key instanceof String) ? (String) key : String.valueOf(key);
//						if(rowIndex < 3){
							data.setValue(rowIndex, columnIndex, xAxisValue);
							columnIndex++;
							if (me.getValue() != null) {
								ArrayList dataValueList = (ArrayList) me.getValue();
								if (dataValueList.size() > 0)
									data.setValue(rowIndex, columnIndex, (Double) dataValueList.get(0));
								columnIndex++;
							}
				
							
							if (inverterMap != null) {
								ArrayList dataValueList = (ArrayList)inverterMap.get(key);
								if (dataValueList != null && dataValueList.size() > 0)
									data.setValue(rowIndex, columnIndex, (Double) dataValueList.get(0));
								columnIndex++;
							}
							
/*							if (batteryMap != null) {
							ArrayList dataValueList = (ArrayList)batteryMap.get(key);
								if (value != null)
									data.setValue(rowIndex, columnIndex, value);
							}
*/							
							
							if (utilityMap != null) {
								ArrayList dataValueList = (ArrayList) utilityMap.get(key);
								if (dataValueList != null && dataValueList.size() > 0)
									data.setValue(rowIndex, columnIndex, (Double) dataValueList.get(0));
								columnIndex++;
							}
							
							if (isDGConfigured && dgMap != null) {
								ArrayList dataValueList = (ArrayList)dgMap.get(key);
								if (dataValueList != null && dataValueList.size() > 0)
									data.setValue(rowIndex, columnIndex, (Double) dataValueList.get(0));
								columnIndex++;
							}
//						}
							rowIndex++;
					}
				}

				
				final Options options = LineChart.createOptions();
				if(equpType.equalsIgnoreCase("Utility"))
					options.setColors("Red");
				
				if(equpType.equalsIgnoreCase("Panel"))
					options.setColors("Green");
				
				if(equpType.equalsIgnoreCase("Inverter"))
					options.setColors("DarkGray");
				
				if(equpType.equalsIgnoreCase("Battery"))
					options.setColors("Blue");
				
				if(equpType.equalsIgnoreCase("D G"))
					options.setColors("IndianRed");
				
//				if(equipmentType.equalsIgnoreCase("All")){
//					options.setColors(sbColors.toString());
//				}
				options.setPointSize(2);
				options.setWidth((getScreenWidth()*72)/100);
				int screenHeight = getScreenHeight();
				if(screenHeight > 1000)
					options.setHeight((screenHeight*35)/100);
				else if(screenHeight > 900 && screenHeight < 1000)
					options.setHeight((screenHeight*40)/100);
				else if(screenHeight > 800 && screenHeight < 900)
					options.setHeight((screenHeight*45)/100);
				else if(screenHeight > 700 && screenHeight < 800)
					options.setHeight((screenHeight*50)/100);
				else if(screenHeight > 600 && screenHeight < 700)
					options.setHeight((screenHeight*55)/100);
				options.setTitle(siteName+" ("+ groupNo+")");
		        HorizontalAxisOptions hao = HorizontalAxisOptions.create();
		        hao.setSlantedText(true);
		        hao.setSlantedTextAngle(60);
		        options.setHAxisOptions(hao);
		        options.setLegend(LegendPosition.BOTTOM);
		        ChartArea chartArea = ChartArea.create();
		        chartArea.setTop("10px");
		        chartArea.setHeight("50%");
		        options.setChartArea(chartArea);
				LineChart lineChart = new LineChart(data, options);
				chartMainTable.setWidget(1, 0, lineChart);
				chartMainTable.getFlexCellFormatter().setWidth(1, 0, "95%");
//				chartMainTable.getFlexCellFormatter().setHeight(1, 0, "100%");
				chartMainTable.getFlexCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_RIGHT);
				chartMainTable.getFlexCellFormatter().setVerticalAlignment(1, 0, HasVerticalAlignment.ALIGN_TOP);
				new Timer() {

					@Override
					public void run() {
					}
				}.scheduleRepeating(10 * 1);
			}
		};
		VisualizationUtils.loadVisualizationApi(onLoadCallback, LineChart.PACKAGE);

	}

	private void loadGauge(final Map<String, List<Integer>> gaugeConf, final List gaugeValue) {

		Runnable onLoadCallback = new Runnable() {
			public void run() {
				Double voltage = (gaugeValue != null && gaugeValue.get(1) != null) ? (Double) gaugeValue.get(1) : 0.0;
				Double current = (gaugeValue != null && gaugeValue.get(2) != null) ? (Double) gaugeValue.get(2) : 0.0;
				Double power = !equipmentType.equalsIgnoreCase("Battery") ? Double.valueOf(NumberFormat.getFormat("#.##").format(voltage * current)) : 0.0;
				Set set = gaugeConf.entrySet();
				Iterator i = set.iterator();
				int cellIndex = 0;
				FlexTable gaugeTable = new FlexTable();
				while (i.hasNext()) {
					Map.Entry<String, List<Integer>> me = (Map.Entry) i.next();
					final DataTable data = DataTable.create();
					data.addColumn(ColumnType.STRING, "Label");
					data.addColumn(ColumnType.NUMBER, "Value");
					data.addRows(1);

					data.setValue(0, 0, me.getKey());
					if (me.getKey().equalsIgnoreCase("Voltage")) {
						data.setValue(0, 1, voltage);
						cellIndex = 0;
					}
					if (me.getKey().equalsIgnoreCase("Current")) {
						data.setValue(0, 1, current);
						cellIndex = 1;
					}
					if (me.getKey().equalsIgnoreCase("Power")) {
						data.setValue(0, 1, power);
						cellIndex = 2;
					}

					List<Integer> meterRangeList = me.getValue();
					Integer min = meterRangeList.get(0);
					Integer max = meterRangeList.get(1);

					final Gauge.Options option = Gauge.Options.create();
					Integer minYellow = meterRangeList.get(2);
					Integer maxYellow = meterRangeList.get(3);
					Integer minGreen = meterRangeList.get(4);
					Integer maxGreen = meterRangeList.get(5);
					Integer minRed = meterRangeList.get(6);
					Integer maxRed = meterRangeList.get(7);
					option.setHeight((getScreenHeight()*18)/100);
					option.setGaugeRange(min, max);
					option.setYellowRange(minYellow, maxYellow);
					option.setGreenRange(minGreen, maxGreen);
					option.setRedRange(minRed, maxRed);
					option.setMinorTicks(10);

					gaugeTable.setWidget(0, cellIndex, new Gauge(data, option));
				}

				chartMainTable.setWidget(3, 0, gaugeTable);
				chartMainTable.getFlexCellFormatter().setStyleName(3, 0, "box_bg");
				chartMainTable.getFlexCellFormatter().setHorizontalAlignment(3, 0, HasHorizontalAlignment.ALIGN_CENTER);
				chartMainTable.getFlexCellFormatter().setVerticalAlignment(3, 0, HasVerticalAlignment.ALIGN_MIDDLE);
				
				new Timer() {

					@Override
					public void run() {
					}
				}.scheduleRepeating(10 * 1);
			}
		};

		VisualizationUtils.loadVisualizationApi(onLoadCallback, Gauge.PACKAGE);

	}

	public static native int getScreenWidth() /*-{
		return $wnd.screen.width;
	}-*/;

	public static native int getScreenHeight() /*-{
		return $wnd.screen.height;
	}-*/;

}
